<template>
  <div class="app-container  bg-gray">
    <transition name="fade-transform" mode="out-in">
      <router-view />
    </transition>
    <el-row v-if="isShow" class="box-1">
      <el-col :span="24">
        <el-card>
          <div class="header">
            <div>
              <el-select v-if="queryMatch(34)" v-model="searchTerms.level" placeholder="客戶等级" clearable @change="getData">
                <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-select v-model="searchTerms.status" placeholder="客戶状态" clearable @change="getData">
                <el-option :value="1" label="已激活" />
                <el-option :value="0" label="已冻结" />
              </el-select>
              <el-select v-if="queryMatch(34)" v-model="searchTerms.source" placeholder="客戶来源" clearable @change="getData">
                <el-option v-for="item in sourceList" :key="item.id" :label="item.source_name" :value="item.source_name" />
              </el-select>
              <el-tooltip content="注册时间" placement="top">
                <el-date-picker
                  v-model="searchTerms.date"
                  :editable="false"
                  class="picker"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  @change="getData"/>
              </el-tooltip>
              <el-input v-if="queryMatch(52)" v-model="searchTerms.min_balance" placeholder="资金起点" class="balance-input1" @change="getData" />
              <div v-if="queryMatch(52)" class="balance-text">-</div>
              <el-input v-if="queryMatch(52)" v-model="searchTerms.max_balance" placeholder="资金终点" class="balance-input2" @change="getData" />
              <el-input v-model="searchTerms.searchValue" placeholder="请输入内容" class="search-input" @change="getData" />
              <el-button type="success" class="do-btn" icon="el-icon-search" @click="getData">搜索</el-button>
              <div class="flex-1" />
              <el-button v-if="queryMatch(30)" type="success" class="bg-green" icon="el-icon-circle-plus" @click="toModify('新增客戶')">新增客戶</el-button>
              <column-controller :check-items="th" class="controller" @change="columnCheck" />
            </div>
          </div>
          <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange">
            <el-table-column prop="id" label="ID" min-width="80" header-align="center" align="center" sortable />
            <el-table-column v-if="th[1].check" prop="name" label="客戶昵称" min-width="100" header-align="center" align="center">
              <template slot-scope="scope">
                {{ scope.row.name?scope.row.name:'--' }}
                <span class="remarks">{{ scope.row.remarks }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="th[2].check" prop="realname" label="真实名" min-width="120" header-align="center" align="center" />
            <el-table-column v-if="th[3].check" prop="mobile" label="手机" min-width="120" header-align="center" align="center" />
            <el-table-column v-if="th[4].check" prop="level_name" label="客戶等级" min-width="120" header-align="center" align="center" />
            <el-table-column v-if="th[5].check" prop="company" label="公司" min-width="160" header-align="center" align="center" >
              <template slot-scope="scope">
                {{ scope.row.company?scope.row.company:'--' }}
              </template>
            </el-table-column>
            <el-table-column v-if="th[6].check&&queryMatch(52)" prop="balance" label="资金" min-width="100" header-align="center" align="center" sortable>
              <template slot-scope="scope">
                <div @click="showMoneyChange(scope.row, '资金')">
                  <el-tag type="primary">{{ scope.row.balance }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="th[7].check&&queryMatch(52)" prop="cash_coupon" label="赠送金" min-width="100" header-align="center" align="center" sortable>
              <template slot-scope="scope">
                <div @click="showMoneyChange(scope.row, '赠送金')">
                  <el-tag type="primary">{{ scope.row.cash_coupon }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="queryMatch(52)" prop="cash_coupon" label="保证金" min-width="100" header-align="center" align="center" sortable>
              <template slot-scope="scope">
                <div @click="showMoneyChange(scope.row, '保证金')">
                  <el-tag type="primary">{{ scope.row.assure_money }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="th[8].check" prop="admin_name" label="跟进人" min-width="100" header-align="center" align="center" />
            <el-table-column v-if="th[9].check" prop="create_time" label="注册时间" min-width="130" header-align="center" align="center" sortable>
              <template slot-scope="scope">
                {{ scope.row.create_time?parseTime(scope.row.create_time, '{y}-{m}-{d}'):'--' }}
              </template>
            </el-table-column>
            <el-table-column label="状态" min-width="80" header-align="center" align="center" fixed="right">
              <template slot-scope="scope">
                <div @click="queryMatch(31)?setState(scope.row):''">
                  <el-tag :type="scope.row.status==0?'danger':'success'">{{ scope.row.status==0?'已冻结':'已激活' }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="250" header-align="center" align="center" fixed="right">
              <template slot-scope="scope">
                <!--<el-button type="primary" size="small" icon="el-icon-search" circle @click="codeDialogVisible=true"/>-->
                <el-tooltip content="跳转代理商" placement="top">
                  <el-button v-if="queryMatch(200)" type="primary" size="small" icon="el-icon-search" circle
                             @click="toAgent(scope.row)"/>
                </el-tooltip>
                <el-tooltip content="完善信息" placement="top">
                  <el-button v-if="queryMatch(31)" type="info" size="small" icon="el-icon-edit" circle
                             @click="toModify('编辑客戶',scope.row)"/>
                </el-tooltip>
                <el-tooltip content="沟通记录" placement="top">
                  <el-button v-if="queryMatch(232)" type="warning" size="small" icon="el-icon-document" circle @click="toCommunicationRecord(scope.row)"/>
                </el-tooltip>
                <el-tooltip content="业绩录入" placement="top">
                  <el-button v-if="queryMatch(93)" type="success" size="small" icon="el-icon-tickets" circle
                             class="bg-green" @click="toAchievement(scope.row)"/>
                </el-tooltip>
                <el-tooltip content="删除客户" placement="top">
                  <el-button v-if="queryMatch(32)" type="danger" size="small" icon="el-icon-delete" circle
                             @click="toDelete(scope.row)"/>
                </el-tooltip>
                <!--<el-tooltip :content="scope.row.isVip?'vip客户':'非vip客户'" placement="top">
                  <el-button :icon="scope.row.isVip?'el-icon-star-on':'el-icon-star-off'" :type="scope.row.isVip?'warning':''" size="small" circle @click="setVip(scope.row)"/>
                </el-tooltip>-->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            :total="total"
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"/>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="codeDialogVisible" :modal-append-to-body="false" title="请用微信扫码打开" align="center" width="480px">
      <img src="@/images/code.jpg" alt="code">
    </el-dialog>
    <!--修改客户资金弹窗-->
    <!--<el-dialog :visible.sync="moneyChangeDialogVisible" :title="form.title+'管理'" width="480px" class="dialog" center @close="resetMoneyChangeDialog('form')">
      <el-form ref="form" :model="form" label-width="90px">
        <el-form-item>
          <el-radio-group v-model="form.doType">
            <el-radio :label="0">增加</el-radio>
            <el-radio :label="1">减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.title==='赠送金'" label="类型">
          <el-select v-model="form.type">
            <el-option :value="1" label="充值赠送" />
            <el-option :value="2" label="活动补贴" />
            <el-option :value="-1" label="冲账" />
            <el-option :value="-2" label="罚款" />
            <el-option :value="3" label="其他" />
          </el-select>
        </el-form-item>
        <el-form-item :label="form.title" prop="label">
          <el-input v-model="form.money" />
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="form.remarks" type="textarea" rows="3"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="moneyChangeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitMoneyChange('form')">确 定</el-button>
      </div>
    </el-dialog>-->
  </div>
</template>

<script>
import { ColumnController } from '../components';
import defaultAvatar from '../../images/default_avatar.png';
import { handleSortChange, handleSizeChange, handleCurrentChange, columnCheck, parseTime } from '../../utils/table';
export default {
  components: { ColumnController },
  data() {
    return {
      isShow: false,
      // ImageUrl: this.$store.getters.serverUrl,
      ImageUrl: '',
      defaultAvatar: defaultAvatar,
      searchTerms: {
        level: '',
        source: '',
        status: '',
        date: [],
        min_balance: '',
        max_balance: '',
        searchValue: ''
      },

      codeDialogVisible: false,

      moneyChangeDialogVisible: false,
      form: {
        title: '资金',
        doType: 0,
        type: 1,
        money: 0,
        remarks: '',
        source: ''
      },

      levelList: [], // 等级列表
      statusList: [], // 状态列表
      sourceList: [], // 来源列表

      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 300,
      th: [{ name: '头像', check: true },
        { name: '客戶名', check: true },
        { name: '真实名', check: true },
        { name: '手机', check: true },
        { name: '客戶等级', check: true },
        { name: '公司', check: true },
        { name: '资金', check: true },
        { name: '赠送金', check: true },
        { name: '跟进人', check: true },
        { name: '注册时间', check: true }],
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: []
    }
  },

  watch: {
    $route(to) {
      if (to.name === '我的客户') {
        this.getData();
        setTimeout(() => {
          this.isShow = true;
        }, 500)
      } else {
        this.isShow = false;
      }
    }
  },
  created() {
    if (this.$route.name === '我的客户') {
      this.isShow = true;
      this.getData();
      this.getLevelList();
      this.getSourceList();
    }
  },

  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange, columnCheck, parseTime,
    /**
     * 对应接口客戶列表("member/list"),
     * token  客戶凭证  (必填)
     * page_no   当前页码
     * page_size   每页数量
     * sortName  排序字段名
     * sortOrder   排序方式
     * search  关键词
     * start_time  注册开始时间
     * end_time  注册结束时间
     * min_balance  最小资金
     * max_balance  最大资金
     * level  客户等级
     * status  客户状态
     * return: {
     *    "name":null,
     *    "status":0,
     *    "mobile":"18870960002",
     *    "create_time":"2018-08-01 05:13:08",
     *    "avatar":null,
     *    "realname":"肖羿",
     *    "company":"官网推广",
     *    "level_name":"普通会员",
     *    "balance":"0.00",
     *    "cash_coupon":"0.00",
     *    "admin_name":"邓家和"
     * }
     * */
    getData(order) {
      this.tableLoading = true;
      order || (order = {});
      const url = 'member/list';
      const data = {
        page_no: this.currentPage,
        page_size: this.pageSize,
        search: this.searchTerms.searchValue,
        level: this.searchTerms.level,
        status: this.searchTerms.status,
        min_balance: this.searchTerms.min_balance,
        max_balance: this.searchTerms.max_balance
      };
      this.searchTerms.date && this.searchTerms.date.length !== 0 && (data.start_time = this.searchTerms.date[0] + ' 00:00:00', data.end_time = this.searchTerms.date[1] + ' 23:59:59');
      order.sortName && (data.sortName = order.sortName);
      order.sortOrder && (data.sortOrder = order.sortOrder);
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.tableData = res.data.rows;
        this.total = res.data.total;
        this.tableLoading = false;
      }).catch(e => {
        this.tableLoading = false;
        this.$message.error(e.msg + ',请刷新或联系管理员');
      })
    },

    /**
     *  获取等级列表
     *  接口:'member/level-list'
     */
    getLevelList() {
      const url = 'member/level-list';
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.levelList = res.data;
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      })
    },

    /**
     *  获取等级列表
     *  接口:'member/source-list'
     */
    getSourceList() {
      const url = 'member/source-list';
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.sourceList = res.data;
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员');
      });
    },

    /**
     * 修改选择客户的赠送金及资金
     */
    showMoneyChange(row, title) {
      this.$router.push({
        path: '/user/userlist/capitalDetail',
        query: {
          id: row.id,
          title: title
        }
      });
    },
    submitMoneyChange(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.form;
          if (this.form.title === '资金') {
            data.c = 'upwallet';
            data.w = this.form.money;
          } else {
            data.c = 'updonationamount';
            data.d = this.form.money;
          }
          const url = 'member/moneyEdit/' + this.form.id
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg);
            this.getData();
            this.moneyChangeDialogVisible = false;
          }).catch((err) => {
            this.$message.error(err.msg);
          })
        } else {
          this.$message.error('提交失败,请检查必填项');
        }
      })
    },

    resetMoneyChangeDialog(formName) {
      this.$refs[formName].resetFields();
    },

    /**
     * 设置当前客戶的状态
     * row: 当前点击的行的数据
     */
    setState(row) {
      row.status = (row.status === 0 ? 1 : 0);
      const url = 'member/ajax/' + row.id;
      const data = { action: 'status', status: row.status };
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.$message.success('修改客戶状态成功，状态：' + (row.status === 1 ? '已激活' : '已冻结'));
      }).catch(e => {
        row.status = row.status === 0 ? 1 : 0;
        this.$message.error('修改客戶状态失败，请刷新或联系管理员');
      })
    },

    /**
     * 设置客户为vip客户
     */
    setVip(row) {
      row['isVip'] = !row['isVip'];
      // const url = 'member/ajax/' + row.id;
      // const data = { action: 'status', status: row.status };
      // this.$store.dispatch('GetConnect', { url, data }).then(res => {
      //   this.$message.success('修改客戶状态成功，状态：' + (row.status === 1 ? '已激活' : '已冻结'));
      // }).catch(e => {
      //   row.status = row.status === 0 ? 1 : 0;
      //   this.$message.error('修改客戶状态失败，请刷新或联系管理员');
      // })
    },

    toAgent(row) {
      const url = '../admin_web_login/' + row.id;
      this.$store.dispatch('GetConnect', { url }).then(res => {
        // const url = 'http://localhost:9529/#/workbench/index?code=' + res.data.token + '&mallId=' + this.$store.getters.SaaSId
        const url = this.$store.getters.serverUrl + '/agent/#/workbench/index?code=' + res.data.token + '&mallId=' + this.$store.getters.SaaSId
        window.open(url)
      }).catch(() => {
        this.$message.error('跳转失败，请刷新或联系管理员');
      })
    },

    /**
     * 跳转客戶修改页面
     * title: 新增/修改
     * row: 当前点击的行的数据,为空时为新增
     */
    toModify(title, row) {
      this.isShow = false;
      const query = { title: title };
      row && (query.id = row.id);
      this.$router.push({
        path: '/user/userlist/modify',
        query: query
      });
    },

    toAchievement(row) {
      this.isShow = false;
      this.$router.push({
        path: '/user/userlist/achievement',
        query: {
          id: row.id
        }
      });
    },
    toCommunicationRecord(row) {
      this.isShow = false;
      this.$router.push({
        path: '/user/userlist/communicationRecord',
        query: {
          id: row.id
        }
      });
    },

    /**
     * 删除客戶
     * row: 当前点击的行的数据
     */
    toDelete(row) {
      this.$confirm('此操作将删除该客户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'member/delete/' + row.id;
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.$message.success(res.msg);
          this.getData();
        }).catch((err) => {
          this.$message.error(err.msg);
        })
      })
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../styles/index.scss';
.box-1 {
  .header {
    @include flex-row(center, space-between);
    padding-bottom: 15px;
    flex-wrap: wrap;
    > div {
      @include flex-row(center, flex-start);
      flex-wrap: wrap;
      width: 100%;
    }
    .el-select {
      padding-right: 15px;
      width: 180px;
    }
    .picker {
      margin-right: 15px;
    }
    .search-input {
      width: 240px;
    }
    .balance-input1 {
      width: 90px;
    }
    .balance-input2 {
      width: 90px;
      margin-right: 15px;
    }
    .balance-text {
      padding: 0 5px;
    }
    .do-btn {
      @extend .bg-green;
      margin-left: 6px;
    }
  }
}
.dialog {
  .content {
    text-align: center;
  }
}
.el-tag {
  cursor: pointer;
}
.remarks{
  font-size: 12px;
  color: $textGray;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  line-height: 0px;
}
</style>
